<template>
  <!--印章模板库-->
  <view>
    <!--提示-->
    <uni-notice-bar color="#00A660" background-color="#f0f9eb" text="根据印章行业标准自动生成印章章面，生成后立即可用。"/>
    <!-- 选择印章样式 -->
    <view>
      <view class="item-title">1、选择印章样式</view>
      <view style="display: flex;align-items: center;width: 100%;">
        <!-- 印章规格列表 -->
        <view class="seal-style-scroll" ref="scrollBox">
          <view v-for="(item,index) in sealStyleList" :key="index" class="seal-style-item"
                @click="goSealStyleCenter($event)">
            <img
                class="seal-style-img"
                :src="ossUrl + item.image"
                :class="(sealStyleSelect != null && sealStyleSelect.id === item.id) ? 'sealSelected' : ''"
                @click="getSealStyle(item)"
            />
            <span class="seal-style-item-title" style="width:150rpx;white-space: normal;">{{ item.name }}</span>
          </view>
        </view>
        <!-- 印章预览 -->
        <view class="seal-preview">
          <img v-if="!!sealGenerateBase64" :src="sealGenerateBase64" class="seal-preview-img"
               @click="previewImg(sealGenerateBase64)"/>
          <span class="seal-style-item-title" style="font-size:22rpx;color: #4c596e;">印章预览</span>
        </view>
      </view>
    </view>
    <!-- 设置印章规格 -->
    <view>
      <view class="item-title">2、设置印章规格</view>
      <uni-forms ref="form" label-position="top" :label-width="150">
        <uni-forms-item label="印章直径" name="name">
          <uni-easyinput
              v-if="sealSpecSelect.shapeType == 0"
              v-model="'直径 '+ sealSpecSelect.mmWidth +'mm'"
              disabled
          ></uni-easyinput>
          <uni-easyinput
              v-else-if="sealSpecSelect.shapeType == 1"
              v-model="sealSpecSelect.mmWidth +'mm * ' +sealSpecSelect.mmWidth+'mm '"
              disabled
          ></uni-easyinput>
          <uni-easyinput
              v-else-if="sealSpecSelect.shapeType == 2"
              v-model="sealSpecSelect.mmWidth +'mm * ' +sealSpecSelect.mmWidth+'mm '"
              disabled
          ></uni-easyinput>
          <uni-easyinput
              v-else
              v-model="sealSpecSelect.mmWidth +'mm * ' +sealSpecSelect.mmWidth+'mm '"
              disabled
          ></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item :label="(sealStyleSelect.insideCircle == 0)?'圆边宽：':'圆边宽(外圆/内圆)：'" style="margin-bottom:15px">
          <uni-easyinput v-if="sealStyleSelect.insideCircle == 0" value="1.2mm" disabled></uni-easyinput>
          <uni-easyinput v-else value="1.2mm / 0.3mm" disabled></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item
            v-if="sealStyleSelect.middlePattern != 0"
            :label="(sealStyleSelect.middlePattern == 1)?'五角星直径：':'党徽直径：'">
          <uni-easyinput value="14mm * 14mm" disabled></uni-easyinput>
        </uni-forms-item>
      </uni-forms>
    </view>
    <!-- 设置印章文字 -->
    <view>
      <view class="item-title">3、设置印章文字</view>
      <uni-forms ref="form" :model="sealTextForm" :rules="sealTextRules" label-position="top" :label-width="150">
        <uni-forms-item
            v-if="sealStyleSelect.englishName == 1"
            label="环排英文文字："
            name="englishName"
            required>
          <uni-easyinput
              v-model="sealTextForm.englishName"
              placeholder="环排英文文字"
              @change="generateCompanySeal"
              :clearable="false"
          ></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item
            :label="(sealStyleSelect.englishName == 1) ? '环排中文文字：' : '环绕文字：'"
            required>
          <uni-easyinput v-model="companyInfo.name" disabled></uni-easyinput>
          <span style="color: #ccc;font-size:12px;">自动获取所属法人企业名称，无法修改</span>
        </uni-forms-item>
        <uni-forms-item
            v-if="sealStyleSelect.horizontalText == 1"
            label="下方横排文字："
            name="sealTitle"
            required>
          <uni-easyinput
              v-model="sealTextForm.sealTitle" placeholder="下方横排文字"
              @change="generateCompanySeal"
              :maxlength="sealSpecSelect.shapeType == 1 ? 15 : 10"
              :clearable="false"
              show-word-limit></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item
            v-if="sealStyleSelect.bottomSealNo == 1"
            label="信息编码："
            required>
          <uni-easyinput v-model="companyInfo.creditCode" disabled></uni-easyinput>
          <span style="color: #ccc;font-size:12px;">自动获取所属企业统一社会信用代码，无法修改</span>
        </uni-forms-item>
      </uni-forms>
    </view>
  </view>
</template>

<script>
import {
  companyCircularChinese,
  companyCircularEnglishInner,
  companyCircularEnglishOuter,
  companyEllipseChinese,
  companyEllipseEnglish,
  initDhImage
} from "@/utils/seal-utils";
import {listSealStyle} from "@/api/ec/console/seal/sealStyle";
import {getSealSpec} from "@/api/ec/console/seal/sealSpec";

export default {
  data() {
    return {
      companyInfo: this.$store.getters.companyInfo,// 企业信息
      // oss链接地址
      ossUrl: this.$ossUrl,
      // 样式图片列表
      sealStyleList: [],
      // 选中的样式
      sealStyleSelect: {},
      // ================================================ 印章规格 =======================================================
      // 印章规格加载中
      specLoading: false,
      // 选中的印章规格
      sealSpecSelect: {},
      // 印章规格form
      sealSpecForm: {},
      // 印章规格校验
      sealSpecRules: {},
      // ================================================ 印章文字 =======================================================
      // 印章文字form
      sealTextForm: {
        englishName: 'XXXX COMPANY LTD.',
        sealTitle: '下方横排文字',
      },
      sealTitleMaxlength: 6,
      // 印章文字校验
      sealTextRules: {
        englishName: {rules: [{required: true, errorMessage: '请输入环排英文文字'}]},
        companyName: {rules: [{required: true, errorMessage: ''}]},
        creditCode: {rules: [{required: true, errorMessage: ''}]},
        sealTitle: {rules: [{required: true, errorMessage: '请输入印章下方横排文字'}]},
      },
      // ================================================ 绘制印章 =======================================================
      // 印章Base64图片字符
      sealGenerateBase64: null,
    }
  },
  created() {
    // 初始化加载党徽素材图片
    initDhImage();
    this.getSealStyleList();
  },
  methods: {
    // ================================================ 印章样式 =======================================================
    /** 印章样式图片列表 */
    getSealStyleList() {
      listSealStyle().then(response => {
        this.sealStyleList = response.data;
        // 默认设置选中第一个
        if (this.sealStyleList != null && this.sealStyleList.length > 0) {
          this.getSealStyle(this.sealStyleList[0]);
        }
      });
    },
    /** 横向滑动居中 */
    goSealStyleCenter(event) {
      let scrollLeft = null
      let scrollRight = null
      let moveDistance = null
      // 宽度的一半
      const clientWidthHalf = this.$refs.scrollBox.clientWidth / 2

      // event.layerX获取元素相对scrollBox元素的位置
      moveDistance = clientWidthHalf - event.layerX
      scrollLeft = moveDistance
      scrollRight = -(moveDistance)

      // 当前元素所在元素的中间位置
      const currentMiddleHalf = (this.$refs.scrollBox.clientWidth + event.target.offsetWidth) / 2
      // 点击左侧
      // 当前的位置坐标
      if (event.layerX <= currentMiddleHalf) {
        this.$refs.scrollBox.scrollLeft -= scrollLeft
      } else {
        // 点击右侧
        this.$refs.scrollBox.scrollLeft += scrollRight
      }

      const res = this.$refs.scrollBox.scrollLeft >= 0 ? this.$refs.scrollBox.scrollLeft : 0
      // 滚动的距离
      this.$refs.scrollBox.scrollLeft = res
    },
    /** 印章选中效果 */
    getSealStyle(item) {
      this.sealStyleSelect = item;
      this.getSealSpecInfo(item.sealSpecId);
    },
    // ================================================ 印章规格 =======================================================
    /** 印章规格信息 */
    getSealSpecInfo(id) {
      this.$modal.loading();
      getSealSpec(id).then(response => {
        uni.hideLoading();
        this.sealSpecSelect = response.data;
        this.sealTextForm.englishName = 'XXXX COMPANY LTD.';
        this.sealTextForm.sealTitle = '下方横排文字';
        this.generateCompanySeal();
      }).catch(() => {
        uni.hideLoading();
      });
    },
    // ================================================ 生成企业印章 =======================================================
    /** 预览印章图片*/
    previewImg(path) {
      uni.previewImage({urls: [path], current: 0});
    },
    /** 生成企业印章图片 */
    generateCompanySeal() {
      if (this.sealSpecSelect == null || this.sealStyleSelect == null) {
        return;
      }
      this.$refs.form.validate().then(valid => {
        if (valid) {
          // 印章Base64图片
          let sealBase64 = "";
          // 英文公司名称
          let englishName = "";
          // 英文企业名画在内圆
          let englishNameInside = 0;
          // 印章横排字
          let sealTitle = "";
          // 印章编号
          let sealNo = "";
          // 是否画中间图案：0不绘制；1五角星；2党徽
          let pattern = 0;
          // 是否画印章内圆：0否；1是
          let insideCircle = 0;

          // 设置英文公司名称
          if (this.sealStyleSelect.englishName == 1) {
            englishName = !!this.sealTextForm.englishName ? this.sealTextForm.englishName : '';
          }
          // 设置印章横排字内容
          if (this.sealStyleSelect.horizontalText == 1) {
            sealTitle = !!this.sealTextForm.sealTitle ? this.sealTextForm.sealTitle : '';
          }
          // 设置印章底部编号内容
          if (this.sealStyleSelect.bottomSealNo == 1) {
            sealNo = this.companyInfo.creditCode;
          }
          // 设置是否画中间图案：0不绘制；1五角星；2党徽
          if (this.sealStyleSelect.middlePattern == 1) {
            pattern = 1;
          } else if (this.sealStyleSelect.middlePattern == 2) {
            pattern = 2;
          } else {
            pattern = 0;
          }
          // 设置是否画印章内圆
          if (this.sealStyleSelect.insideCircle == 1) {
            insideCircle = 1;
          } else {
            insideCircle = 0;
          }
          // 设置英文企业名画在内圆：0否；1是
          if (this.sealStyleSelect.englishNameInside == 1) {
            englishNameInside = 1;
          } else {
            englishNameInside = 0;
          }
          if (this.sealSpecSelect.shapeType == 0) {
            // =================================================== 圆形印章 ==================================================
            if (this.sealStyleSelect.englishName == 0) {
              // 绘圆形印章（中文）
              sealBase64 = companyCircularChinese(this.companyInfo.name, sealTitle, sealNo, pattern, insideCircle, 0, 0);
            } else {
              // 绘制（外资）圆形签章（中英文）
              if (englishNameInside == 0) {
                // 英文在外圆
                sealBase64 = companyCircularEnglishOuter(this.companyInfo.name, englishName, sealNo, 0, 0);
              } else {
                // 英文在内圆
                sealBase64 = companyCircularEnglishInner(this.companyInfo.name, englishName, sealNo, 0, 0);
              }
            }
          } else if (this.sealSpecSelect.shapeType == 1) {
            // =================================================== 椭圆印章 ==================================================
            if (this.sealStyleSelect.englishName == 0) {
              // 绘制椭圆签章（中文）
              sealBase64 = companyEllipseChinese(this.companyInfo.name, sealTitle, sealNo, 0, 0);
            } else {
              // 绘制（外资）椭圆签章（中英文）
              sealBase64 = companyEllipseEnglish(this.companyInfo.name, englishName, sealNo, 0, 0);
            }
          }
          this.sealGenerateBase64 = sealBase64;
          // 回调图片结果
          this.$emit('success', this.sealSpecSelect, this.sealGenerateBase64, sealTitle, englishName);
        }
      });
    },
  }
}
</script>

<style scoped lang="scss">
.item-title {
  font-weight: bold;
  font-size: 26rpx;
  color: #606266;
  margin: 15rpx 0;
}

.item-step {
  height: 50rpx;
  line-height: 50rpx;
  font-size: 26rpx;
  color: #606266;
  margin-left: 15rpx;
}

.seal-style-scroll {
  width: 100%;
  overflow-x: scroll;
  height: auto;
  white-space: nowrap;
  margin-right: 15rpx;
}

.seal-style-item {
  display: inline-block;
  text-align: center;
  margin-right: 10rpx;
  vertical-align: top;
  cursor: pointer;
}

.sealSelected {
  border: 1px solid #00a660 !important;
}

.seal-style-item-title {
  font-size: 20rpx;
  color: #777777;
  display: block;
  line-height: normal;
  min-height: 30rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical
}

.seal-style-img {
  border: 1px solid #e5e7ea;
  width: 120rpx;
  height: 120rpx;
  cursor: pointer;
  object-fit: contain;
  padding: 10rpx;
}

.seal-preview {
  display: inline-block;
  text-align: center;
  width: 200rpx;
  //margin-left: 20rpx;
}

.seal-preview-img {
  border: 2rpx dashed #ccc;
  width: 180rpx;
  height: 180rpx;
  display: inline-block;
  padding: 10rpx;
  object-fit: contain;
}
</style>
